package com.polaris.live.ui.login

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.util.DisplayMetrics
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ColorUtils
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.polaris.live.R
import com.polaris.live.adapter.LoginBackAdapter
import com.polaris.live.common.AppModule
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.ServerConfig
import com.polaris.live.common.event.EventStringMessage
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.util.DateUtils
import com.polaris.live.constant.EventConst
import com.polaris.live.constant.TrackEventConst
import com.polaris.live.constant.TrackEventConst.EVENT_AGREEMENT_UC
import com.polaris.live.constant.TrackEventConst.EVENT_LOGIN_GMAIL_UC
import com.polaris.live.constant.TrackEventConst.EVENT_LOGIN_GOOGLE_UC
import com.polaris.live.constant.TrackEventConst.EVENT_LOGIN_PHONE_UC
import com.polaris.live.constant.TrackEventConst.EVENT_LOGIN_QUICK_UC
import com.polaris.live.constant.TrackEventConst.EVENT_LOGIN_UV
import com.polaris.live.databinding.ActivityLoginBinding
import com.polaris.live.dialog.DmaDialog
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.dialog.PrivacyConfirmDialog
import com.polaris.live.interface_bag.XpopupCallBackImpl
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.resp.event.AppVersionUpdateEvent
import com.polaris.live.resp.event.ConfigInitializedEvent
import com.polaris.live.resp.event.IpCountryInitializedEvent
import com.polaris.live.translation.R.string
import com.polaris.live.utils.AppConfigUtils
import com.polaris.live.utils.DmaUtils
import com.polaris.live.utils.TrackHelper
import com.polaris.live.utils.postEvent
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.utils.route.SpanClickUtils
import com.polaris.live.utils.sensor.impl.ServerModuleHelper
import com.polaris.live.viewmodel.login.LoginViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 登录页 LoginActivity
 *
 * @author Created by 半仙 on 2023/8/9/009 11:13
 */
class LoginActivity : BaseGoogleLoginActivity<LoginViewModel, ActivityLoginBinding>() {

    private var mIsCheck = true

    private var mIsCheckedDma = false

    private val mAdapter by lazy { LoginBackAdapter() }

    private val mList = listOf("", "", "", "", "")

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .statusBarDarkFont(false)
            .transparentBar()
            .init()
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        mBinding.backRecycler.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context)
            itemAnimator = null
        }
        mAdapter.addData(mList)
        mBinding.backRecycler.setOnTouchListener { _, event -> true }
        mBinding.viewPleaseHolder.setOnTouchListener { _, event -> true }
        scrollRecyclerViewToBottom(mBinding.backRecycler)

        Firebase.analytics.postEvent(EventConst.PAGE_LOGIN)
        TrackHelper.trackActivity(this, EVENT_LOGIN_UV, TrackEventConst.TRACK_PAGE)

        EventBus.getDefault().register(this)

        mViewModel.getIp()

        val span = SpanClickUtils.with(mBinding.privacyAgreement)
            .append(" ${resources.getText(string.prive_first)}")
            .append(" ${resources.getText(string.terms_of_service)}")
            .setClickSpan(object : ClickableSpan() {
                override fun updateDrawState(paint: TextPaint) {
                    paint.isUnderlineText = true
                    paint.bgColor = Color.TRANSPARENT
                }

                override fun onClick(widget: View) {
                    RouterUtils.routerGoto(CommonConst.Agreement.TERMS_OF_SERVICE)
                }
            })
            .setForegroundColor(ColorUtils.getColor(R.color.white))
            .append(" ${resources.getText(string.prive_and)}")
            .append(" ${resources.getText(string.privacy_policy)}")
            .setClickSpan(object : ClickableSpan() {
                override fun updateDrawState(paint: TextPaint) {
                    paint.isUnderlineText = true
                    paint.bgColor = Color.TRANSPARENT
                }

                override fun onClick(widget: View) {
                    RouterUtils.routerGoto(CommonConst.Agreement.PRIVACY_POLICY)
                }
            })
            .setForegroundColor(ColorUtils.getColor(R.color.white))
            .append(" ${resources.getText(string.prive_and)}")
            .append(" ${resources.getText(string.prive_last)}")
            .setClickSpan(object : ClickableSpan() {
                override fun updateDrawState(paint: TextPaint) {
                    paint.isUnderlineText = true
                    paint.bgColor = Color.TRANSPARENT
                }

                override fun onClick(widget: View) {
                    RouterUtils.routerGoto(CommonConst.Agreement.CONVENTION)
                }
            })
            .setForegroundColor(ColorUtils.getColor(R.color.white)).create()
        mBinding.privacyAgreement.text = span
        val showFacebookLogin = AppConfigManager.getConfig(CommonConst.Configs.showFacebookLogin) ?: "0"
//        showFacebookLogin(showFacebookLogin)

        initListener()
        initObserver()
        if (ServerConfig.isDebug() || !ServerConfig.isProdServer()) {
            ServerModuleHelper.attach(this)
        }
    }

    // 自定义 SmoothScroller 控制滚动速度
    class SlowScroller(context: Context) : LinearSmoothScroller(context) {

        override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
            return 10.0f // 控制滚动速度
        }

        override fun calculateTimeForDeceleration(dx: Int): Int {
            // 禁用减速效果，直接返回根据dx的滚动时间
            return (dx / 2).coerceAtLeast(1)
        }
    }

    // 滚动 RecyclerView 到底部
    private fun scrollRecyclerViewToBottom(recyclerView: RecyclerView) {
        recyclerView.post {
            val scroller = SlowScroller(recyclerView.context)
            scroller.targetPosition = recyclerView.adapter?.itemCount ?: 0
            recyclerView.layoutManager?.startSmoothScroll(scroller)
        }
    }

    private fun initListener() {
        mBinding.backRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val totalItemCount = layoutManager.itemCount
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()

                // 判断是否滑动到底部  这里不能用滑动状态做判断， 当停止的时候SlowScroller需要重新处理
                if (lastVisibleItemPosition == totalItemCount - 2) {
                    mAdapter.addData(mList)
                    scrollRecyclerViewToBottom(mBinding.backRecycler)
                    if (mAdapter.data.size >= 20) {
                        mAdapter.notifyItemRangeRemoved(0, 10)
                    }
                }
            }
        })
        mBinding.cbPrivacy.setOnCheckedChangeListener { _, isChecked ->
            mIsCheck = isChecked
            if (isChecked) {
                mBinding.ivBottomArrow.visibility = View.INVISIBLE
                mBinding.tvPleaseRead.visibility = View.INVISIBLE
            } else {
                mBinding.ivBottomArrow.visibility = View.VISIBLE
                mBinding.tvPleaseRead.visibility = View.VISIBLE
            }
            val isManual = mBinding.cbPrivacy.isPressed // 判断是否是手动操作
            if (isManual) {
                TrackHelper.trackActivity(this, EVENT_AGREEMENT_UC)
            }
        }
        mBinding.selectQuick.setOnSingleClickListener {
            Firebase.analytics.postEvent(EventConst.CLICK_QUICK_LOGIN)

            TrackHelper.trackActivity(this, EVENT_LOGIN_QUICK_UC)

            gotoLogin(LoginViewModel.GOTO_DEVICE)
        }
        mBinding.selectPhoneLogin.setOnSingleClickListener {
            Firebase.analytics.postEvent(EventConst.CLICK_PHONE_LOGIN)

            TrackHelper.trackActivity(this, EVENT_LOGIN_PHONE_UC)

            gotoLogin(LoginViewModel.GOTO_PHONE)
        }
        mBinding.selectGmailLogin.setOnSingleClickListener {
            Firebase.analytics.postEvent(EventConst.CLICK_GMAIL_LOGIN)

            TrackHelper.trackActivity(this, EVENT_LOGIN_GMAIL_UC)

            gotoLogin(LoginViewModel.GOTO_GMAIL)
        }
        mBinding.selectGoogleLogin.setOnSingleClickListener {
            Firebase.analytics.postEvent(EventConst.CLICK_GOOGLE_LOGIN)

            TrackHelper.trackActivity(this, EVENT_LOGIN_GOOGLE_UC)

            gotoGoogleLoginAndCheck(mIsCheck) {
                mBinding.cbPrivacy.isChecked = true
            }
        }
        mBinding.ivArrow.setOnClickListener {
            handleFacebookButton(!it.isSelected)
        }
    }

    private fun gotoLogin(type: Int) {
        if (!mIsCheck) {
            XPopup.Builder(AppModule.mApplication)
                .isDestroyOnDismiss(true)
                .setPopupCallback(object : XpopupCallBackImpl {

                    override fun onShow(popupView: BasePopupView) {
                        super.onShow(popupView)
                        TrackHelper.trackActivity(
                            this@LoginActivity,
                            TrackEventConst.EVENT_ITEM_UC,
                            TrackEventConst.TRACK_DIALOG
                        )
                    }
                })
                .asCustom(
                    PrivacyConfirmDialog(
                        this,
                        callBack = {
                            if (it) {
                                TrackHelper.trackActivity(
                                    this@LoginActivity,
                                    TrackEventConst.EVENT_CONTINUE_UC
                                )
                                mBinding.cbPrivacy.isChecked = true
                                mViewModel.gotoLogin(type)
                            } else {
                                TrackHelper.trackActivity(
                                    this@LoginActivity,
                                    TrackEventConst.EVENT_CLOSE_UC
                                )
                            }
                        })
                )
                .show()
        } else {
            mViewModel.gotoLogin(type)
        }
    }

    private fun initObserver() {
        mViewModel.ipLiveData.observe(this) {
            if (it != null) {
                checkDma(it)
            }
        }
    }

    private fun checkDma(ipCountry: String) {
        //如果ip发现是欧盟国家，则需要需要做特殊处理
        DmaDialog.checkAndShowDmaDialog(this, ipEea = DmaUtils.isEEA(ipCountry))
        mIsCheckedDma = true
    }

    private fun showFacebookLogin(showFacebookLogin: String) {
        if (showFacebookLogin == "2") {
            handlePhoneButton(false)

            mBinding.ivArrow.visibility = View.GONE
        } else {
            handleFacebookButton(showFacebookLogin == "1", false)
        }
    }

    private fun handleFacebookButton(show: Boolean, phoneShow: Boolean? = null) {
        mBinding.selectGmailLogin.visibility = if (show) View.VISIBLE else View.GONE

        val finalPhoneShow = handlePhoneButton(phoneShow ?: show)

        mBinding.ivArrow.isSelected = show && finalPhoneShow
        if (mBinding.ivArrow.isSelected) {
            mBinding.ivArrow.setImageResource(R.drawable.select_login_arrow_icon_up)
        } else {
            mBinding.ivArrow.setImageResource(R.drawable.select_login_arrow_icon_down)
        }
    }

    private fun handlePhoneButton(show: Boolean): Boolean {
        return if (show || AppConfigUtils.isShowPhoneButton()) {
            mBinding.selectPhoneLogin.visibility = View.VISIBLE
            true
        } else {
            mBinding.selectPhoneLogin.visibility = View.GONE
            false
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEventBus(event: EventStringMessage) {
        when (event.from) {
            BizEventConst.LOGIN_FINISH -> {
                finish()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onVersionUpdateEvent(event: AppVersionUpdateEvent) {
        EventBus.getDefault().removeStickyEvent(event)
        if (event.version.forceUpdate) {
            GlobalDialogManager.showUpgradeDialog(this, event.version)
        } else {
            val date = CacheUtil.getUpdateVersionTime(event.version.buildVersion.toString())
            if (date == 0L || !DateUtils.isOneDay(date, System.currentTimeMillis())) {
                CacheUtil.setUpdateVersionTime(event.version.buildVersion.toString())
                GlobalDialogManager.showUpgradeDialog(this, event.version)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPostInitEvent(event: ConfigInitializedEvent) {
        AppConfigManager.getConfig(CommonConst.Configs.showFacebookLogin)?.also {
            showFacebookLogin(it)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onIpCountryInitializedEvent(event: IpCountryInitializedEvent) {
        if (mIsCheckedDma) {
            return
        }
        checkDma(event.ipCountry)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}